﻿using MediatR;
using RBAC.Domain;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class DeleteRoleHandler : IRequestHandler<DeleteRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly ILogger<DeleteRoleHandler> logger;

        public DeleteRoleHandler(IBaseRepository<RoleModel> roleRepository, ILogger<DeleteRoleHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var role = roleRepository.GetModel(request.Id);
            role.IsDeleted = true;
            roleRepository.Update(role);
            var roleperssion = roleRepository.GetALL().Where(x => x.Id == request.Id).ToList();
            foreach (var item in roleperssion)
            {
                item.IsDeleted = true;
                roleRepository.Update(item);
            }
            res.Code = APIEnums.Success;
            res.Msg = "删除成功";
            res.Data = 1;
            logger.LogInformation("删除成功");
            return Task.FromResult(res);
        }
    }
}
